﻿using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using TZL.Data;
using TZL.Web.Data;
using System.Linq;
using System.Collections.Generic;
using System.Net.Mail;
using System.Net;

namespace TZL.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //banner
            var banner = SqlDataHelper.Instance.SelectConfig("banner");
            ViewBag.Banner = banner;

            //active
            var active = SqlDataHelper.Instance.SelectNews(9, 1, 8);
            ViewBag.Active = active;

            //school
            var school = SqlDataHelper.Instance.SelectNews(1, 1, 6);
            ViewBag.School = school;

            return View();
        }

        public ActionResult SchoolDetail(int id)
        {
            var model = SqlDataHelper.Instance.SelectNewsById(id);
            return PartialView(model);
        }

        public ActionResult QuicklyApply()
        {
            return View();
        }

        public ActionResult uploadfile()
        {
            var q = Request.Files;
            return null;
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Contact()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Contact(EmailModel model)
        {
            try
            {
                MailMessage mm = new MailMessage();
                mm.From = new MailAddress(model.email);
                mm.To.Add("chrismiaow@gmail.com");
                mm.Subject = model.name + ": 来信";
                mm.Body = "Name: " + model.name + "<br/><br/>Email: " + model.email + "<br/><br/>" + model.message;

                mm.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
                smtp.Credentials = new NetworkCredential("actapatech@gmail.com", "wmlw1213");
                smtp.EnableSsl = true;
                smtp.Send(mm);
            }
            catch { }
            return View();
        }
        #region 用户上传的文件      
        public ActionResult UploadFiles(string userName, string fileKind, string email, string phone)
        {
            if (Request.Files == null)
            {
                return Content("<script>alert('上传失败'); window.history.go(-1);</script>");
            }


            for (var i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];
                if (file == null || file.ContentLength <= 0)//当前文件为空则继续循环
                {
                    continue;
                }

                var extension = Path.GetExtension(file.FileName);

                if (extension == null || !".doc|.docx|.pdf".Contains(extension))
                {
                    return Content("<script>alert('文件格式不支持，只支持 (.doc|.docx|.pdf)'); window.history.go(-1);</script>");
                }
            }

            var userId = GetUserFileId(new UserFile
            {
                UserName = userName,
                Email = email,
                Phone = phone,
                UploadTime = DateTime.Now
            });

            if (userId == 0)//userId不存在则退出
            {
                return Json(new { result = false });
            }
            string[] kinds = fileKind.Split(',');
            var files = new List<UploadFile>();
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];
                if ((file == null || file.ContentLength <= 0))//当前文件为空则继续循环
                {
                    continue;
                }
                string pathForSaving = Server.MapPath("~/Upload/File");
                if (CreateFolderIfNeeded(pathForSaving))
                {
                    //获取文件名和文件扩展名
                    var extension = Path.GetExtension(file.FileName);
                    if (extension == null || !".doc|.docx|.pdf".Contains(extension))
                    {
                        return Content("<script>alert('文件格式不支持，只支持 (.doc|.docx|.pdf)'); window.history.go(-1);</script>");
                    }

                    string filename = file.FileName.Replace(extension, "") + kinds[i] + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
                    var path = Path.Combine(pathForSaving, filename);
                    file.SaveAs(path);

                    files.Add(new UploadFile
                    {
                        UserID = userId,
                        FileKinds = kinds[i],
                        CreateTime = DateTime.Now,
                        FileAdress = "../Upload/File/" + Path.GetFileName(filename)
                    });
                }
            }

            if (files.Count > 0)
            {
                using (var context = new PortalEntities())
                {
                    context.UploadFiles.AddRange(files);
                    var count = context.SaveChanges();
                    if (count > 0)
                    {
                        //return Json(new { resut = false });
                        return Content("<script>alert('上传成功'); window.history.go(-1);</script>");
                    }
                }
            }
            return Content("<script>alert('上传失败'); window.history.go(-1);</script>");//
        }

        public int GetUserFileId(UserFile user)
        {
            using (var context = new PortalEntities())
            {
                context.UserFiles.Add(user);
                var count = context.SaveChanges();
                if (count > 0)
                {
                    var queryId = (from item in context.UserFiles
                                   where item.UserName == user.UserName
                                   select item).FirstOrDefault();
                    if (queryId.Id > 0)
                    {
                        return queryId.Id;
                    }
                }
            }
            return 0;
        }

        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    //TODO：处理异常
                    result = false;
                }
            }
            return result;
        }

        #endregion

        public class EmailModel
        {
            public string name { get; set; }
            public string email { get; set; }
            public string message { get; set; }
        }
    }
}